package studio.raptor.hub.in.config;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import studio.raptor.hub.in.properties.HttpConnectionProperties;

/**
 * http连接配置
 *
 * @author jack
 * @since 1.0
 */
@Configuration
public class HubInHttpConnectionConfig {


  @Bean
  @ConfigurationProperties(prefix = "extractor.http")
  public HttpConnectionProperties httpConnectionProperties() {
    return new HttpConnectionProperties();
  }

  @Bean
  public ClientHttpRequestFactory httpRequestFactory() {
    return new HttpComponentsClientHttpRequestFactory(httpClient());
  }

  @Bean
  @ConditionalOnBean(HttpConnectionProperties.class)
  public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager() {
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
        .register("http", PlainConnectionSocketFactory.getSocketFactory())
        .register("https", SSLConnectionSocketFactory.getSocketFactory())
        .build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
        registry);
    connectionManager.setMaxTotal(httpConnectionProperties().getMaxTotal());
    connectionManager.setDefaultMaxPerRoute(httpConnectionProperties().getDefaultMaxPerRoute());
    return connectionManager;
  }

  @Bean(name = "hubInHttpClient")
  @ConditionalOnBean(HttpConnectionProperties.class)
  public HttpClient httpClient() {
    RequestConfig requestConfig = RequestConfig.custom()
        .setSocketTimeout(httpConnectionProperties().getSocketTimeout())
        .setConnectionRequestTimeout(httpConnectionProperties().getConnectionRequestTimeout())
        .setConnectTimeout(httpConnectionProperties().getConnectTimeout())
        .build();
    return HttpClientBuilder.create()
        .setDefaultRequestConfig(requestConfig)
        .setConnectionManager(poolingHttpClientConnectionManager())
        .build();
  }

}
